#include "pointlistform.h"
#include "ui_pointlistform.h"

PointListForm::PointListForm(Geocaching *aProg, QWidget *parent) :
    QWidget(parent), ui(new Ui::PointListForm), myProg(aProg)
{
    ui->setupUi(this);
    setFixedSize(size());
    connect(myProg, SIGNAL(PointAdded(Point)), this, SLOT(UpdateForm()));
    connect(myProg, SIGNAL(PointDeleted(ulong)), this, SLOT(UpdateForm()));
    connect(myProg, SIGNAL(PointEdited(Point)), this, SLOT(UpdateForm()));
}

PointListForm::~PointListForm()
{
    if(ui)  delete ui;
}

void PointListForm::activateWindow()
{
    UpdateForm();
}

void PointListForm::UpdateForm(void)
{
    ui->pointListWidget->clear();
    ui->propertyListWidget->clear();
    QList <Point> formPointList = myProg->GetPointList();
    foreach(Point tmpPoint, formPointList)
    {
        QListWidgetItem *item = new QListWidgetItem(tmpPoint.GetName(), ui->pointListWidget);
        item->setData(Qt::UserRole, static_cast<qulonglong>(tmpPoint.GetID()));
        item->setText(tmpPoint.GetName());
    }
    QListWidgetItem *item = ui->pointListWidget->currentItem();
    if(!item)
    {
        ui->editPointButton->setEnabled(false);
        ui->deletePointButton->setEnabled(false);
    }
    else
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        ui->editPointButton->setEnabled(tmpID);
        ui->deletePointButton->setEnabled(tmpID);
    }
}


void PointListForm::on_addPointButton_clicked()
{
    AddPointDialog apDialog;
    apDialog.setWindowFlags(apDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
    if(apDialog.exec())
    {
        Point tmpPoint;
        if(apDialog.Result(&tmpPoint))
            myProg->AddPoint(&tmpPoint);
    }
}

void PointListForm::on_editPointButton_clicked()
{
    QListWidgetItem *item = ui->pointListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        Point tmpPoint;
        if(myProg->GetPoint(tmpID, &tmpPoint))
        {
            EditPointDialog epDialog(&tmpPoint);
            epDialog.setWindowFlags(epDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
            if(epDialog.exec())
                if(epDialog.Result())
                    myProg->EditPoint(tmpID, &tmpPoint);
        }
    }
}

void PointListForm::on_deletePointButton_clicked()
{
    QListWidgetItem *item = ui->pointListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        myProg->DeletePoint(tmpID);
    }
}

void PointListForm::on_pointListWidget_doubleClicked(const QModelIndex& /*index*/)
{
    ui->propertyListWidget->clear();
    QListWidgetItem *item = ui->pointListWidget->currentItem();
    if(item)
    {
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        Point tmpPoint;
        if(myProg->GetPoint(tmpID, &tmpPoint))
        {
            GeoCoordinates tmpCoord = tmpPoint.GetCoordinates();
            QString tmpString;
            unsigned long N = tmpPoint.GetFileCount();
            QListWidgetItem *itemProperty = new QListWidgetItem(tmpPoint.GetName(), ui->propertyListWidget);
            tmpString.sprintf("Широта: %lf", tmpCoord.GetLatitude());
            itemProperty = new QListWidgetItem(tmpString, ui->propertyListWidget);
            tmpString.sprintf("Долгота: %lf", tmpCoord.GetLongitude());
            itemProperty = new QListWidgetItem(tmpString, ui->propertyListWidget);
            if(N > 0)   tmpString.sprintf("Список привязанных файлов.");
            else        tmpString.sprintf("Нет привязанных файлов.");
            itemProperty = new QListWidgetItem(tmpString, ui->propertyListWidget);
            for(unsigned long i = 0; i < N; ++i)
            {
                QListWidgetItem *itemFile = new QListWidgetItem(tmpPoint.GetFileName(i), ui->propertyListWidget);
                itemFile->setData(Qt::UserRole, tmpPoint.GetFileName(i));
                itemFile->setWhatsThis("FILE");
            }
        }
    }
}

void PointListForm::on_pointFindLineEdit_returnPressed()
{
    if(!ui->pointFindLineEdit->text().isEmpty())
    {
        unsigned long findStartNumber = ui->pointListWidget->currentRow(), N = ui->pointListWidget->count();
        for(unsigned long i = ++findStartNumber; i < N; ++i)
        {
            QString tmpString = ui->pointListWidget->item(i)->text();
            tmpString.resize(ui->pointFindLineEdit->text().size());
            if(!tmpString.compare(ui->pointFindLineEdit->text()))
            {
                ui->pointListWidget->setCurrentRow(i);
                return;
            }
        }
        for(unsigned long i = 0; i < findStartNumber; ++i)
        {
            QString tmpString = ui->pointListWidget->item(i)->text();
            tmpString.resize(ui->pointFindLineEdit->text().size());
            if(!tmpString.compare(ui->pointFindLineEdit->text()))
            {
                ui->pointListWidget->setCurrentRow(i);
                return;
            }
        }
    }
}

void PointListForm::on_propertyListWidget_doubleClicked(const QModelIndex& /*index*/)
{
    QListWidgetItem *item = ui->propertyListWidget->currentItem();
    if(item && (item->whatsThis() == "FILE"))
    {
        QString file_name = item->data(Qt::UserRole).toString();
        file_name = QDir::cleanPath(file_name);
        if(!QFile::exists(file_name))
        {
            QMessageBox::warning(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Файл не существует!");
            return;
        }
        if(!QDesktopServices::openUrl(QUrl(QUrl::fromLocalFile(file_name))))
        {
            QMessageBox::information(QApplication::activeWindow(), QApplication::applicationName(),
            "Невозможно открыть файл `" + file_name + "`. Не найдена программа для его открытия!");
            return;
        }
    }
}

void PointListForm::on_pointListWidget_currentRowChanged(int currentRow)
{
    ui->propertyListWidget->clear();
    if(currentRow == -1)
    {
        ui->editPointButton->setEnabled(false);
        ui->deletePointButton->setEnabled(false);
    }
    else
    {
        QListWidgetItem *item = ui->pointListWidget->currentItem();
        unsigned long tmpID = item->data(Qt::UserRole).toULongLong();
        ui->editPointButton->setEnabled(tmpID);
        ui->deletePointButton->setEnabled(tmpID);
    }
}
